package game.controller;

import game.model.Block;
import game.model.Board;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class NormalCreate implements CreateRule {
    @Override
    public boolean createBlocks(Board board) {
        List<Integer> empty_blocks = this.getEmptyBlocks(board); // 空的位置
        if (empty_blocks.isEmpty()) return false;

        Random random = new Random();

        int index = random.nextInt(empty_blocks.size() / 2) * 2; // 选择一个
        int x = empty_blocks.get(index), y = empty_blocks.get(index + 1);
        int value = (random.nextDouble() < 0.75) ? 2 : 4; // 75% 是 2， 25% 是 4
        board.setBlock(x, y, new Block(value));
        return true;
    }

    /**
     * 获取空白方格
     *
     * @return 每两个数字描述一个下标
     */
    private List<Integer> getEmptyBlocks(Board board) {
        List<Integer> emptyBlocks = new ArrayList<Integer>();
        for (int i = 0; i < board.getWidth(); ++i) {
            for (int j = 0; j < board.getHeight(); ++j) {
                if (board.getBlock(i, j) == null) {
                    emptyBlocks.add(i);
                    emptyBlocks.add(j);
                }
            }
        }
        return emptyBlocks;
    }
}
